import { memo, useEffect, useState } from 'react';
import { Input, Button, AutoComplete, Tag } from 'antd';
import type { AutoCompleteProps } from 'antd';
import useWindowWidth from '@/hooks/event/use-window-width';
import { SvgIcon } from '@/components/icon';
const { TextArea } = Input;
import { useChatPage } from '@/store/configStore';
import { useRouter } from '@/router/hooks';
import { useNavigate } from 'react-router-dom';

import { CloseOutlined } from '@ant-design/icons';

interface Props {
  handleSend: (message: string) => void;
  handleInterrupt: () => void;
  changeInputType: () => void;
  isMessageSend: boolean;
  voice: boolean;
}

const MessageSendInput = ({
  handleSend,
  handleInterrupt,
  changeInputType,
  isMessageSend,
  voice,
}: Props) => {
  const navigate = useNavigate();

  const { isPc } = useWindowWidth();
  const [inputValue, setInputValue] = useState('');
  const [tag, setTag] = useState([]);
  const chatPage = useChatPage();
  const router = useRouter();
  const [actOptions, setActOptions] = useState({ value: '应用推荐', id: 1 });

  const [options, setOptions] = useState<AutoCompleteProps['options']>([]);
  const onSelect = (value, option) => {
    console.log('onSelect', option);
    setTag([option]);
    setInputValue('');
  };

  const demoOptions = [{ value: '应用推荐', id: 1 }];

  const handleSearch = (value: string) => {
    // console.log('value===========', value);

    if (value == '@' && tag.length == 0) {
      setOptions(demoOptions);
    } else {
      setOptions([]);
    }
  };

  useEffect(() => {
    if (tag.length > 0 && options?.length != 0) {
      setOptions([]);
    }
  }, [tag.length]);

  const handleKeyDown = (e) => {
    if (e?.key === 'Delete' || e?.keyCode === 46 || e?.key === 'Backspace' || e?.keyCode === 8) {
      if (!inputValue) {
        setTag([]);
        setOptions([]);
      }
    }

    if (e?.key === 'Enter' && e?.keyCode === 13 && !e?.shiftKey) {
      if (inputValue == '@' && tag.length == 0) {
        setTag([option]);
        setInputValue('');
      }
      e.preventDefault();

      if (!inputValue) {
        return;
      }

      if (tag?.length > 0) {
        handleSend('@' + tag[0]?.value + ' ' + inputValue);
      } else {
        handleSend(inputValue);
      }

      setInputValue('');
    }
  };

  const handleBtnClicked = () => {
    if (isMessageSend) {
      handleInterrupt();
    } else {
      if (inputValue.trim().length == 0) {
        changeInputType();
      } else {
        if (tag?.length > 0) {
          handleSend('@' + tag[0]?.value + ' ' + inputValue);
        } else {
          handleSend(inputValue);
        }

        setInputValue('');
      }
    }
  };

  const textareaStyle = {
    borderRadius: '6px',
    resize: 'none',
    overflowY: 'scroll',
    width: '100%',
    outline: 'none',
    boxShadow: 'none',
    backgroundColor: '#fff',
    scrollbarWidth: 'none',
    flexGrow: 1,
    borderWidth: 0,
    lineHeight: '30px',
  };

  return (
    <div
      className="arae-outlined"
      style={{
        display: isPc ? 'flex' : 'block',
        width: '100%',
        flexDirection: 'column',
        // border: '1px solid #D1C5FF',
        backgroundColor: '#fff',
        borderRadius: '16px',
        padding: '5px',
        position: 'relative',
      }}
    >
      {tag?.length > 0 && (
        <div style={{ marginBottom: '0px' }}>
          {tag?.map((item, index) => {
            return (
              <Tag
                style={{
                  borderRadius: '5px',
                  padding: '0px 10px',
                  fontSize: '14px',
                  display: 'inline-flex',
                  alignItems: 'center',
                  backgroundColor: 'f3f5fc',
                  fontWeight: 'bold',
                }}
                bordered={false}
                key={index}
                closable
                onClose={() => {
                  setTag([]);
                }}
              >
                @{item.value}
              </Tag>
            );
          })}
        </div>
      )}
      <div style={{ display: 'flex', width: '100%' }}>
        <AutoComplete
          className="ant-select"
          options={options}
          maxLength={2000}
          onSelect={onSelect}
          onSearch={handleSearch}
          getPopupContainer={(triggerNode) => triggerNode.parentElement}
          dropdownStyle={{
            position: 'absolute',
            top: '100%',
            left: 0,
            marginTop: -120,
            zIndex: 1000,
            borderRadius: '12px',
            width: '100%',
          }}
          // dropdownRender={dropdownRender}
          value={inputValue}
          style={{
            width: '100%',
            flex: '1 1 auto',
            height: '100%',
          }}
        >
          <TextArea
            id="question"
            className="focu border:none "
            // rows={tag?.length > 0 ? 3 : 4}
            autoSize={{ minRows: 2, maxRows: 8 }}
            onChange={(e) => setInputValue(e.target.value)}
            value={inputValue}
            onKeyDown={handleKeyDown}
            placeholder={
              isPc
                ? tag?.length == 0
                  ? '@召唤应用推荐，输入问题，发送【Enter】/ 换行【Shift+Enter】'
                  : '输入问题，发送【Enter】/ 换行【Shift+Enter】'
                : '输入问题'
            }
            style={textareaStyle}
          />
        </AutoComplete>
      </div>

      <div className="flex justify-end">
        <Button
          className="flex "
          id="submit"
          type="text"
          size="small"
          icon={
            isMessageSend ? (
              <SvgIcon icon="ic_stop" size={25} />
            ) : inputValue.trim().length == 0 ? (
              voice ? (
                <SvgIcon icon="ic_rj_keyboard" size={25} />
              ) : (
                <SvgIcon icon="ic_rj_sound" size={25} />
              )
            ) : (
              <SvgIcon icon="ic_rj_send" size={25} />
            )
          }
          onClick={handleBtnClicked}
          style={{
            color: '#fff',
            borderRadius: '16px',
            width: '60px',
            height: '30px',
            backgroundColor: '#6640ff',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            alignSelf: 'flex-end',
            justifySelf: 'end',
          }}
        />
      </div>
    </div>
  );
};

export default memo(MessageSendInput);
